/**
 * 
 */
package com.thoughtworks.merchantsguide.processor;

import org.apache.commons.lang.StringUtils;

import com.thoughtworks.merchantsguide.cache.ComodityPriceCache;
import com.thoughtworks.merchantsguide.commodity.Matter;
import com.thoughtworks.merchantsguide.commodity.Metal;
import com.thoughtworks.merchantsguide.common.Utility;
import com.thoughtworks.merchantsguide.exception.UnsupportedNumberException;

/**
 * This processor, parses the input and store the price of commodity in the
 * cache, that can be used by customer query.
 *
 */
public class CommodityPriceProcessor implements LineProcessor {

	private static final String CREDIT_IN_QUERY = " Credit";
	private static final String IS_FOR_INDEX = " is ";

	/**
	 * This method parses the input string and finds the price of each
	 * commodity. input: <br/>
	 * "glob glob Silver is 34 Credits" <br/>
	 * This method returns the matter object that is extracted from the input
	 * after calculating the price.
	 * 
	 * @throws UnsupportedNumberException
	 * 
	 * @see com.thoughtworks.merchantsguide.processor.LineProcessor#process(java.lang.String)
	 */
	@Override
	public Object process(String query) throws UnsupportedNumberException {
		int indexOfis = StringUtils.indexOf(query, IS_FOR_INDEX);
		String subString = query.substring(0, indexOfis);

		int lastIndexOfSpace = StringUtils.lastIndexOf(subString, SPACE_FOR_SEARCH);
		String galacticNumbers = subString.substring(0, lastIndexOfSpace);
		String matter = subString.substring(lastIndexOfSpace + 1);
		// Find the price which is in-between " is " and " Credit".
		long totalPrice = Long.valueOf(StringUtils.substringsBetween(query, IS_FOR_INDEX, CREDIT_IN_QUERY)[0]);
		Matter aMatter = new Metal();
		aMatter.setName(matter);
		aMatter.setValue(totalPrice / Utility.getArabicFromGalacticNumber(galacticNumbers));
		ComodityPriceCache.addSupportedMatter(aMatter);
		return aMatter;
	}



}
